package cn.quevo.ucenter.core;

import java.net.URI;
import java.net.URISyntaxException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import cn.quevo.core.enums.ResultStatusEnum;
import cn.quevo.core.lang.StringUtils;
import cn.quevo.ucenter.core.entity.OauthResponse;

public class ResponseEntityBuild {

    private final static Logger log = LoggerFactory.getLogger(ResponseEntityBuild.class);

    /**
     * 构造ResponseEntity
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月26日 下午1:27:57
     * @return
     */
    public static ResponseEntity<Object> build(HttpStatus httpStatus, OauthResponse response) {
        return new ResponseEntity<Object>(response.buildJson(), httpStatus);
    }

    public static ResponseEntity<Object> ok(OauthResponse response) {
        return new ResponseEntity<Object>(response.buildJsonBody(), HttpStatus.OK);
    }

    /**
     * 302跳转
     * 
     * @author July july_sky@foxmail.com
     * @date 2018年3月26日 下午1:35:00
     * @return
     */
    public static ResponseEntity<Object> found(OauthResponse response) {
        if (StringUtils.isBlank(response.getRedirectUri())) {
            return build(HttpStatus.BAD_REQUEST, new OauthResponse(ResultStatusEnum.PARAMS_INCOMPLETE));
        }
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(new URI(response.getLocationUri()));
            return new ResponseEntity<>(headers, HttpStatus.FOUND);
        } catch (URISyntaxException e) {
            log.error(e.getMessage(), e);
            return build(HttpStatus.BAD_REQUEST, new OauthResponse(ResultStatusEnum.PARAMS_INCOMPLETE));
        }
    }
}
